package com.ybf.api.builder;

import com.ybf.api.utils.Utils;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.context.Context;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.util.*;
import java.util.stream.Collectors;

public class CodeGenerator {

    private List<GenerateFile> generateFileList;

    public CodeGenerator (List<GenerateFile> generateFileList) {
        this.generateFileList = generateFileList;
    }

    public void start () {
        this.generateFileList.forEach((item) -> {
            // 链接数据库读取数据库表结构
            List<Table> tableColumns = getTableInfo(item.getTableName());
            // 渲染
            item.getFileTemplateInfoList().forEach((fItem) -> {
                renderTemplate(item.getEntityName(), item.getTableName(), tableColumns, fItem.getTemplatePath(), fItem.getOutPutPath());
            });
        });
    }


    public List<Table> getTableInfo(String tableName) {
//        String url = "jdbc:mysql://81.68.194.209:30004/y_toolbox";
        String url = "jdbc:mysql://localhost:3306/y_toolbox";
//        String url = "jdbc:sqlite:sql/y-toolbox-sqlite3";
        String user = "root";
        String password = "bing2840";
        List<Table> tableColumns = new ArrayList<Table>();

        try (Connection conn = DriverManager.getConnection(url, user, password)) {
            // 获取数据库元数据
            DatabaseMetaData metaData = conn.getMetaData();

            System.out.println("Table Name: " + tableName);

            // 获取表的列信息
            ResultSet columnRs = metaData.getColumns(null, null, tableName, "%");

            while (columnRs.next()) {
                String columnName = columnRs.getString("COLUMN_NAME");
                int dataType = columnRs.getInt("DATA_TYPE");
                String typeName = columnRs.getString("TYPE_NAME");
                int columnSize = columnRs.getInt("COLUMN_SIZE");
                int nullable = columnRs.getInt("NULLABLE"); // 0 = NO NULLS, 1 = NULLS ALLOWED
                String remarks = columnRs.getString("REMARKS");

                Map<String, String> typeMap = new HashMap<>();
                typeMap.put("VARCHAR", "String");
                typeMap.put("CHAR", "String");
                typeMap.put("TEXT", "String");
                typeMap.put("DOUBLE", "double");
                typeMap.put("BOOLEAN", "boolean");
                typeMap.put("BIGINT UNSIGNED", "Integer");
                typeMap.put("BIGINT", "Integer");
                typeMap.put("INT", "Integer");
                typeMap.put("DATE", "Date");
                typeMap.put("TIMESTAMP", "Timestamp");

                System.out.println("Column Name: " + columnName);
                System.out.println("typeName: " + typeName);


                tableColumns.add(new Table(
                        Utils.toCamelCase(columnName),
                        columnName,
                        typeMap.get(typeName),
                        columnSize,
                        nullable,
                        remarks,
                        dataType
                ));
            }
            // 关闭列结果集
            columnRs.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return tableColumns;
    }

    public void renderTemplate(String entityName, String tableName, List<Table> tableColumns, String templatePath, String outputPath) {
        // 初始化 Velocity 引擎
        VelocityEngine velocityEngine = initializeVelocity("src/main/java/com/ybf/api/builder/templates");

        // 获取表字段名字符串数组
        String tableColumnNames = tableColumns.stream()
                .map(Table::getColumnNameBase)
                .collect(Collectors.joining(", "));

        // 数据模型
        Context context = new VelocityContext();
        context.put("entityName", entityName);
        context.put("tableName", tableName);
        context.put("tableColumns", tableColumns);
        context.put("tableColumnNames", tableColumnNames);

        // 渲染模板并输出到新文件
        renderTemplateToFile(velocityEngine, context, templatePath, outputPath);
    }

    private VelocityEngine initializeVelocity(String templatesBasePaths) {
        // 创建并配置 Velocity 引擎
        Properties props = new Properties();
//        props.setProperty("file.resource.loader.path", templatesBasePaths); // 设置模板路径
        props.setProperty("resource.loader.file.path", templatesBasePaths); // 设置模板路径
//        props.setProperty("input.encoding", "UTF-8"); // 设置输入文件的编码
        props.setProperty("resource.default_encoding", "UTF-8"); // 设置输入文件的编码
        props.setProperty("output.encoding", "UTF-8"); // 设置输出文件的编码

        VelocityEngine velocityEngine = new VelocityEngine(props);
        velocityEngine.init();
        return velocityEngine;
    }


    private void renderTemplateToFile(VelocityEngine velocityEngine, Context context, String templatePath, String outputPath) {
        try (FileWriter writer = new FileWriter(new File(outputPath))) {
            velocityEngine.mergeTemplate(templatePath, "UTF-8", context, writer);
            System.out.println("模板渲染成功： " + outputPath);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
